//
//  GGVideoManager.m
//  录制视频
//
//  Created by 聚点互动iOS on 2020/12/22.
//


#import "GGVideoManager.h"
#import "GGVideoManager+FileHelper.h"
#import <GPUImage/GPUImage.h>
#import "GGFilterHandler.h"

@interface GGVideoManager ()<GPUImageVideoCameraDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/** 摄像头 */
@property (nonatomic,strong) GPUImageVideoCamera *videoCamera;


@property (nonatomic, strong) GGFilterHandler *filterHandler;


/** 视频输出视图 */
@property (nonatomic, weak) GPUImageView *outputView;

/** 视频写入 */
@property (nonatomic,strong) GPUImageMovieWriter *movieWriter;

/** 视频写入的地址URL */
@property (nonatomic,strong) NSURL *movieURL;

/** 视频写入路径 */
@property (nonatomic,copy) NSString *moviePath;


/** 视频时长 */
@property (nonatomic,assign) int seconds;

/** 系统计时器 */
@property (nonatomic,strong) NSTimer *timer;

/** 计时器常量 */
@property (nonatomic,assign) int recordSecond;

@end

@implementation GGVideoManager

static GGVideoManager *_manager;

// 单例
+(instancetype)manager {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[GGVideoManager alloc] init];
    });
    return _manager;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_manager == nil) {
            _manager = [super allocWithZone:zone];
        }
    });
    return _manager;
}

- (GGFilterHandler *)filterHandler{
    if (!_filterHandler) {
        GGFilterHandler *filterHandler = [GGFilterHandler new];
        _filterHandler = filterHandler;
    }
    return _filterHandler;
}

// 开始录制
-(void)startRecording {
    
    NSString *defultPath = [self getVideoPathCache];
    self.moviePath = [defultPath stringByAppendingPathComponent:[self getVideoNameWithType:@"mp4"]];
    // 录制路径
    self.movieURL = [NSURL fileURLWithPath:self.moviePath];
    // ？
    unlink([self.moviePath UTF8String]);
    
    
    /// 此处的size是保存后视频的帧图片大小，要和裁剪后的视频比例保持一致，不然视频画面会被压缩或者拉伸
    CGFloat width = 480;
    // 如果出现绿边，在此处解决
    CGSize size = CGSizeMake(width, width * 1.0);
    
    
    self.movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:size];
    self.movieWriter.encodingLiveVideo = YES;
    self.movieWriter.shouldPassthroughAudio = YES;
   
    //添加滤镜
    [self.filterHandler.lastFilter addTarget:self.movieWriter];
    
    
    self.videoCamera.audioEncodingTarget = self.movieWriter;
    // 开始录制
    [self.movieWriter startRecording];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didStartRecordVideoWithVideoManager:)]) {
        [self.delegate didStartRecordVideoWithVideoManager:self];
    }
    [self.timer setFireDate:[NSDate distantPast]];
    [self.timer fire];
    
}

// 结束录制
-(void)endRecording {
    
    if ([self.videoCamera.captureSession isRunning]) {
        
        [self.timer invalidate];
        self.timer = nil;
        __weak typeof(self) weakSelf = self;
        [self.movieWriter finishRecordingWithCompletionHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.delegate && [self.delegate respondsToSelector:@selector(didEndRecordVideoWithVideoManager:time:outputFile:)]) {
                    [weakSelf.delegate didEndRecordVideoWithVideoManager:weakSelf time:self.seconds outputFile:self.moviePath];
                }
            });
        }];
        //移除beatuifyFilter
        //[self.beautifyFilter removeTarget:self.movieWriter];
        
        //移除饱和度滤镜
        [self.filterHandler.lastFilter removeTarget:self.movieWriter];
        
        self.videoCamera.audioEncodingTarget = nil;
        if (self.recordSecond > self.maxTime) {
            
            // 清除录制的视频
            
        }else {
            
        }
    }
}

// 暂停
-(void)pauseRecording {
    
    if ([_videoCamera.captureSession isRunning]) {
        [self.timer invalidate];
        self.timer = nil;
        [_videoCamera pauseCameraCapture];
    }
    
}

// 恢复
-(void)resumeRecording {
    
    [_videoCamera resumeCameraCapture];
    [self.timer setFireDate:[NSDate distantPast]];
    [self.timer fire];
}


#pragma mark -- 自定义方法
/**
 添加图像输出的控件，不会被持有
 */
- (void)addOutputView:(GPUImageView *)outputView{
    self.outputView = outputView;
}

/**
 开启相机，开启前请确保已经设置 outputView
 */
- (void)startCapturing{
    [self.videoCamera addTarget:self.filterHandler.firstFilter];
    [self.filterHandler.lastFilter addTarget:self.outputView];
    
    [self.videoCamera startCameraCapture];
}


// 切换前后摄像头
-(void)changeCameraPosition:(GGVideoManagerCameraType)type {
    
    switch (type) {
        case GGVideoManagerCameraTypeFront:{
            [_videoCamera rotateCamera];
        }
            break;
        case GGVideoManagerCameraTypeBack:{
            [_videoCamera rotateCamera];
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark ----摄像头输出代理方法----
- (void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer{
    
}

// 手电筒开关
-(void)turnTorchOn:(BOOL)on {
    
    if ([_videoCamera.inputCamera hasTorch] && [_videoCamera.inputCamera hasFlash]) {
        
        [_videoCamera.inputCamera lockForConfiguration:nil];
        if (on) {
            [_videoCamera.inputCamera setTorchMode:AVCaptureTorchModeOn];
            [_videoCamera.inputCamera setFlashMode:AVCaptureFlashModeOn];
        }else{
            [_videoCamera.inputCamera setTorchMode:AVCaptureTorchModeOff];
            [_videoCamera.inputCamera setFlashMode:AVCaptureFlashModeOff];
        }
        [_videoCamera.inputCamera unlockForConfiguration];
        
    }
    
}


#pragma mark -- 懒加载

// 摄像头
-(GPUImageVideoCamera *)videoCamera {
    
    if (_videoCamera == nil) {
        _videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionBack];
        _videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        _videoCamera.horizontallyMirrorFrontFacingCamera = YES;
        _videoCamera.delegate = self;
        // 可防止允许声音通过的情况下,避免第一帧黑屏
        [_videoCamera addAudioInputsAndOutputs];
    }
    return _videoCamera;
}


// 计时器
-(NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateWithTime) userInfo:nil repeats:YES];
    }
    return _timer;
}

// 超过最大录制时长结束录制
-(void)updateWithTime {
    
    self.recordSecond++;
    if (self.recordSecond >= self.maxTime) {
        [self endRecording];
    }
    
}


- (void)dealloc {
    
    [self.timer invalidate];
    NSLog(@"销毁了啊");
    
}

@end

